package com.jinzihan.service.impl;

import com.jinzihan.dao.ClassroomDao;
import com.jinzihan.dao.OrderDao;
import com.jinzihan.dao.impl.ClassroomDaoImpl;
import com.jinzihan.dao.impl.OrderDaoImpl;
import com.jinzihan.entity.Classroom;
import com.jinzihan.entity.Order;
import com.jinzihan.entity.Page;
import com.jinzihan.service.OrderService;

import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    ClassroomDao classroomDao = new ClassroomDaoImpl();
    @Override
    public void createOrder(Order order) {
        orderDao.saveOrder(order);
    }

    @Override
    public List<Order> myOrders(int StudentId) {
        return orderDao.queryMyOrders(StudentId);
    }

    @Override
    public List<Order> allOrders() {
        return orderDao.queryAllOrders();
    }

    @Override
    public Classroom orderDetails(int orderId) {
        int classroomId = orderDao.queryClassroomId(orderId);
        return classroomDao.queryClassroomById(classroomId);
    }

    @Override
    public void acceptOrder(int orderId) {
        orderDao.changeOrderStatus(2,orderId);
    }

    @Override
    public void refuseOrder(int orderId) {
        orderDao.changeOrderStatus(1,orderId);
    }

    @Override
    public Page<Order> page(int pageNo, int pageSize) {
        Page<Order> page = new Page<>();

        page.setPageSize(pageSize);

        Integer pageTotalCount = orderDao.queryForOrderCount();
        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal = pageTotalCount / pageSize;
        if (pageTotalCount % pageSize > 0 ){
            pageTotal += 1;
        }
        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);

        int begin = (page.getPageNo() - 1) * pageSize;
        List<Order> items = orderDao.queryForPageItems(begin,pageSize);
        page.setItems(items);
        return page;
    }

    public Page<Order> myPage(int studentId, int pageNo, int pageSize) {
        Page<Order> page = new Page<>();

        page.setPageSize(pageSize);

        Integer pageTotalCount = orderDao.queryForMyOrderCount(studentId);
        page.setPageTotalCount(pageTotalCount);

        Integer pageTotal = pageTotalCount / pageSize;
        if (pageTotalCount % pageSize > 0 ){
            pageTotal += 1;
        }
        page.setPageTotal(pageTotal);

        page.setPageNo(pageNo);

        int begin = (page.getPageNo() - 1) * pageSize;
        List<Order> items = orderDao.queryForMyPageItems(studentId,begin,pageSize);
        page.setItems(items);
        return page;
    }

    @Override
    public Order queryOrderById(int id) {
        return orderDao.queryForOrderById(id);
    }
}
